package com.yunfeisoft.controller.business;

import com.alibaba.excel.EasyExcel;
import com.applet.base.BaseController;
import com.applet.utils.*;
import com.yunfeisoft.business.model.ProductCategory;
import com.yunfeisoft.business.service.inter.CodeBuilderService;
import com.yunfeisoft.business.service.inter.ProductCategoryService;
import com.yunfeisoft.excel.listener.ProductCategoryExcelListener;
import com.yunfeisoft.model.User;
import com.yunfeisoft.utils.ApiUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.*;

/**
 * ClassName: ProductCategoryController
 * Description: 商品类别Controller
 * Author: Jackie liu
 * Date: 2020-07-23
 */
@Controller
public class ProductCategoryController extends BaseController {

    @Autowired
    private ProductCategoryService productCategoryService;
    @Autowired
    private CodeBuilderService codeBuilderService;

    /**
     * 添加商品类别
     *
     * @param record
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/web/productCategory/save", method = RequestMethod.POST)
    @ResponseBody
    public Response save(ProductCategory record, HttpServletRequest request, HttpServletResponse response) {
        Validator validator = new Validator();
        validator.required(request, "name", "名称为空");
        validator.required(request, "pinyinCode", "拼音简码为空");
        if (validator.isError()) {
            return ResponseUtils.warn(validator.getMessage());
        }

        record.setId(KeyUtils.getKey());
        record.setIdPath(record.getId());
        record.setNamePath(record.getName());

        User user = ApiUtils.getLoginUser();
        record.setOrgId(user.getOrgId());
        record.setParentId(Constants.ROOT);

        String code = codeBuilderService.generateCode("PRODUCT_CATEGORY_" + Constants.ROOT, 2, user.getOrgId());
        record.setCode(code);

        productCategoryService.save(record);
        return ResponseUtils.success("保存成功");
    }

    /**
     * 修改商品类别
     *
     * @param record
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/web/productCategory/modify", method = RequestMethod.POST)
    @ResponseBody
    public Response modify(ProductCategory record, HttpServletRequest request, HttpServletResponse response) {
        Validator validator = new Validator();
        validator.required(request, "id", "参数错误");
        validator.required(request, "name", "名称为空");
        validator.required(request, "pinyinCode", "拼音简码为空");
        if (validator.isError()) {
            return ResponseUtils.warn(validator.getMessage());
        }
        productCategoryService.modify(record);
        return ResponseUtils.success("保存成功");
    }

    /**
     * 查询商品类别
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/web/productCategory/query", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Response query(HttpServletRequest request, HttpServletResponse response) {
        String id = ServletRequestUtils.getStringParameter(request, "id", null);
        if (StringUtils.isBlank(id)) {
            return ResponseUtils.warn("参数错误");
        }
        ProductCategory record = productCategoryService.load(id);
        return ResponseUtils.success(record);
    }

    /**
     * 分页查询商品类别
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/web/productCategory/list", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Response list(HttpServletRequest request, HttpServletResponse response) {
        String parentId = ServletRequestUtils.getStringParameter(request, "parentId", null);
        String name = ServletRequestUtils.getStringParameter(request, "name", null);

        User user = ApiUtils.getLoginUser();

        Map<String, Object> params = new HashMap<String, Object>();
        initParams(params, request);
        params.put("name", name);
        params.put("idPath", parentId);
        params.put("orgId", user.getOrgId());

        Page<ProductCategory> page = productCategoryService.queryPage(params);
        return ResponseUtils.success(page);
    }

    /**
     * 批量删除商品类别
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/web/productCategory/delete", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Response delete(HttpServletRequest request, HttpServletResponse response) {
        String ids = ServletRequestUtils.getStringParameter(request, "ids", null);
        if (StringUtils.isBlank(ids)) {
            return ResponseUtils.warn("参数错误");
        }
        productCategoryService.remove(ids.split(","));
        return ResponseUtils.success("删除成功");
    }

    /**
     * 查询商品类别树
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/web/productCategory/loadTree", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Response loadTree(HttpServletRequest request, HttpServletResponse response) {
        User user = ApiUtils.getLoginUser();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put("orgId", user.getOrgId());
        List<ProductCategory> list = productCategoryService.queryList(params);

        List<Tree> treeList = new ArrayList<>();
        for (ProductCategory item : list) {
            Tree tree = new Tree(item.getId(), item.getParentId(), item.getName());
            treeList.add(tree);
        }
        return ResponseUtils.success(treeList);
    }

    /**
     * 拖拽组织机构信息改变从属节点
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/web/productCategory/drag", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Response drag(HttpServletRequest request, HttpServletResponse response) {
        String id = ServletRequestUtils.getStringParameter(request, "id", null);
        String targetId = ServletRequestUtils.getStringParameter(request, "targetId", null);
        if (StringUtils.isBlank(id) || StringUtils.isBlank(targetId)) {
            return ResponseUtils.warn("拖拽参数错误");
        }

        productCategoryService.modifyWithDrag(id, targetId);
        return ResponseUtils.success("拖拽成功");
    }

    /**
     * 导出excel
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/web/productCategory/exportExcel", method = {RequestMethod.POST, RequestMethod.GET})
    public void exportExcel(HttpServletRequest request, HttpServletResponse response) {
        String name = ServletRequestUtils.getStringParameter(request, "name", null);

        User user = ApiUtils.getLoginUser();

        Map<String, Object> params = new HashMap<String, Object>();
        params.put("name", name);
        params.put("orgId", user.getOrgId());

        List<ProductCategory> list = productCategoryService.queryList(params);
        try {
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("商品类别_" + DateUtils.getNowTime(), "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");

            // 根据用户传入字段 假设我们要忽略 date
            Set<String> excludeColumnFiledNames = new HashSet<String>();
            excludeColumnFiledNames.add("id");
            excludeColumnFiledNames.add("orgId");
            excludeColumnFiledNames.add("parentId");
            excludeColumnFiledNames.add("idPath");
            excludeColumnFiledNames.add("namePath");
            excludeColumnFiledNames.add("isDel");
            excludeColumnFiledNames.add("exists");
            excludeColumnFiledNames.add("createTime");
            excludeColumnFiledNames.add("modifyTime");
            excludeColumnFiledNames.add("createId");
            excludeColumnFiledNames.add("modifyId");

            // 这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), ProductCategory.class)
                    .excludeColumnFiledNames(excludeColumnFiledNames)
                    .autoCloseStream(Boolean.FALSE)
                    .sheet("商品类别")
                    .doWrite(list);

        } catch (Exception e) {
            e.printStackTrace();
            // 重置response
            response.reset();
            //response.setContentType("application/json");
            //response.setCharacterEncoding("utf-8");
            AjaxUtils.ajaxJsonWarnMessage("下载失败");
        }
    }

    /**
     * 导入excel
     *
     * @param request
     * @param response
     * @return
     */
    @RequestMapping(value = "/web/productCategory/importExcel", method = {RequestMethod.POST, RequestMethod.GET})
    @ResponseBody
    public Response importExcel(@RequestParam("file") MultipartFile file, HttpServletRequest request, HttpServletResponse response) {
        try {
            User user = ApiUtils.getLoginUser();
            EasyExcel.read(file.getInputStream(), ProductCategory.class, new ProductCategoryExcelListener(user.getOrgId(), user.getId())).sheet().doRead();
        } catch (IOException e) {
            e.printStackTrace();
            return ResponseUtils.success("解析导入文件异常");
        }
        return ResponseUtils.success("导入成功");
    }
}
